using System;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;

namespace UMC.Net;
public class NetCache
{
    long Size = 0;
    static NetCache _instance = new NetCache();
    public static NetCache Share => _instance;

    MemoryMappedFile mmf;

    private NetCache()
    {
        string filePath = Path.GetTempFileName();

        mmf = MemoryMappedFile.CreateFromFile(filePath, FileMode.OpenOrCreate, null, Int32.MaxValue);// MemoryMappedFile.CreateOrOpen("MyMemoryMap", 1024 * 1024);// MemoryMappedFile.CreateFromFile(Path.GetTempFileName());
    }
    public NetCache(string fileName)
    {
        mmf = MemoryMappedFile.CreateFromFile(fileName, FileMode.OpenOrCreate, null, Int32.MaxValue);// MemoryMappedFile.CreateOrOpen("MyMemoryMap", 1024 * 1024);// MemoryMappedFile.CreateFromFile(Path.GetTempFileName());
    }
    public long Append(byte[] bytes, int offset, int size)
    {
        if (size == 0)
        {
            return 0;
        }
        if (Size + size > Int32.MaxValue)
        {
            Size = 0;
        }

        var postion = Interlocked.Add(ref Size, size) - size;
        using (var stream = mmf.CreateViewStream(postion, size))
        {
            stream.Write(bytes, offset, size);
            stream.Flush();
        }
        return postion;
    }
    public long Append(ReadOnlySpan<byte> bytes)
    {
        int size = bytes.Length;
        if (size == 0)
        {
            return 0;
        }
        if (Size + size > Int32.MaxValue)
        {
            Size = 0;
        }

        var postion = Interlocked.Add(ref Size, size) - size;
        using (var stream = mmf.CreateViewStream(postion, size))
        {
            stream.Write(bytes);
            stream.Flush();
        }
        return postion;
    }
    public Stream CreateAccessor(long postion, int size)
    {
        return mmf.CreateViewStream(postion, size);
    }


}